<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取元素到文档顶部的距离</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html {
            height: 100%;
        }
        body {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .test {
            min-width: 25px;
            min-height: 25px;
            border-radius: 5px;
            border: 1px solid #dedede;
            font-size: 2.5rem;
            padding: 15px;
        }
    </style>
</head>

<body>
    <div id="test" class="test"></div>
    <script>
        const getVerticalOffset = el => {
            let offsetTop = el.offsetTop,
                _el = el;

            while (_el.offsetParent) {
                _el = _el.offsetParent;
                offsetTop += _el.offsetTop;
            }

            return offsetTop;
        }
        const test = document.querySelector("#test");
        test.innerHTML = '当前id为test的div元素距离文档顶部的距离为:' + getVerticalOffset(test);
    </script>
</body>

</html>